package com.hue.concurrent.day02;

import java.util.Random;

/*
    转账问题的线程安全
 */
public class Demo04 {
    private static Random random = new Random();

    public static void main(String[] args) {
        Object lock = new Object();
        Account a = new Account(1000, lock);
        Account b = new Account(1000, lock);

        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                a.transferTo(b, getRandom());
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                b.transferTo(a, getRandom());
            }
        }).start();

        while (Thread.activeCount() > 2) {
            Thread.yield();
        }

        System.out.println("总金额:" + (a.getMoney() + b.getMoney()));
    }

    //产生1-100的随机数
    public static int getRandom() {
        return random.nextInt(100) + 1;
    }
}

class Account {
    private int money;
    private Object lock;

    public Account(int money, Object lock) {
        this.money = money;
        this.lock = lock;
    }

    public int getMoney() {
        return money;
    }

    //转账
    public void transferTo(Account account, int count) {
        synchronized (lock) {
            if (money > count) {
                this.money -= count;
                account.money += count;
            }
        }
    }
}
